/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.svm.funds.service.plugins  
 */
package com.apache.funds.service.plugins;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.funds.entity.SvmCaptionBalance;
import com.apache.funds.manager.SvmCaptionBalanceManager;
import com.apache.funds.util.Constants;
import com.apache.funds.util.FundsTemplate;
import com.apache.funds.vo.UserFundsVo;
import com.apache.tools.DateUtils;
import com.apache.tools.ReflectionUtils;

/**
 * 本类主要涉及业务逻辑<br>
 * 1.资金的期初+发生余额的计算提供类  
 * @author goldocean 创建时间：2015-1-14  
 * 
 */
public class FundsOpenAndOccurBalancePlugin implements PluginConnector {
	private Logger log = LoggerFactory.getLogger(getClass());

	private SvmCaptionBalanceManager svmCaptionBalanceManager;

	public void setSvmCaptionBalanceManager(SvmCaptionBalanceManager svmCaptionBalanceManager) {
		this.svmCaptionBalanceManager = svmCaptionBalanceManager;
	}

	/**
	 * TODO 期初+发生的日终处理
	 * @see com.apache.api.manager.PluginConnector#execute(com.apache.api.vo.ParamsVo)  
	 */
	@Override
	public Object execute(ParamsVo vo) throws Exception {
		log.info("【期初+发生日终处理】start....");
		ResultEntity re = new ResultEntity();
		re.setResult("true");
		re.setEntity("false");
		re.setMessage("执行失败");

		// 获取今天的日期
		long dateTrade = 0;
		if (Validator.isEmpty(vo.getParams("dateTrade"))) {
			dateTrade = DateUtils.getSystemDate().getTime();
		} else {
			dateTrade = Long.valueOf(String.valueOf(vo.getParams("dateTrade")));
		}
		vo.setParams("dateTrade", dateTrade);
		vo.setParams("dateFlag", dateTrade);
		Date d = DateUtils.fromLong(dateTrade);
		Date yd = DateUtils.beforeNDays(d, 1);
		long dateTradeYesterday = DateUtils.toLong(yd);
		vo.setParams("dateTradeYesterday", dateTradeYesterday);
		log.info("处理阶段：期初日期:[" + dateTradeYesterday + " - "
				+ DateUtils.format(DateUtils.fromLong(dateTradeYesterday), "yyyyMMdd") + "],发生日期[" + dateTrade + " - "
				+ DateUtils.format(DateUtils.fromLong(dateTrade), "yyyyMMdd") + "]");
		// 获取期初+发生的结果集
		List list = (List) svmCaptionBalanceManager.execute(vo);
		if (list != null && list.size() > 0) {
			log.info("本阶段需要处理的记录数：" + list.size());
			// 获取下一个工作日
			//			Map<String, Object> map = new HashMap<String, Object>();
			//			map.put("methodType", "after");
			//			String today = DateUtils.longToStr(dateTrade, FmtStr.yyyyMMdd).replace("-", "");
			//			map.put("dataTime", today);
			//			map.put("dayNum", "1");
			//			ResultEntity reNextWorkDay = LoadRpcService.service()
			//					.doService("rulesService", "workday", "XML", map, null);
			//			String nextDateStr = DateUtils.format(DateUtils.tomorrow(), "yyyy-MM-dd");
			//			String nextDateStr = DateUtils.getToday();
			//			long nextDate = DateUtils.toLong(DateUtils.parse(nextDateStr));
			//			if (reNextWorkDay != null && "true".equals(reNextWorkDay.getResult())) {
			//				String dateTimeStr = String.valueOf(reNextWorkDay.getEntity());
			//				nextDateStr = dateTimeStr.substring(0, 4) + "-" + dateTimeStr.substring(4, 6) + "-"
			//						+ dateTimeStr.substring(6);
			//				nextDate = DateUtils.toLong(DateUtils.parse(nextDateStr));
			//			}
			// 批量保存
			List<SvmCaptionBalance> listSCB = this.buildListSCB(list, dateTrade);

			for (SvmCaptionBalance scb : listSCB) {
				log.info(scb.getUserId() + "|" + scb.getCaptionId() + "|" + scb.getBalance());
			}

			vo.setObjs(listSCB);
			/*try {
				svmCaptionBalanceManager.saveInfo(vo);
				
				re.setEntity("true");
				re.setMessage("执行成功");
			} catch (Exception e) {
				e.printStackTrace();
				re.setEntity("false");
				re.setMessage("执行异常:" + e.getMessage());
			}*/

			vo.setMethodKey("OpenAndOccurBalance");
			//循环标识
			boolean doFlag = true;
			do {
				String saveFlag = "false";
				//执行批量添加
				try {
					saveFlag = svmCaptionBalanceManager.saveInfo(vo);
				} catch (Exception e) {
					log.info("执行异常:" + e.getMessage());
				}
				//设置循环标识
				if ("true".equals(saveFlag)) {
					log.info("【期初+发生日终处理】信息保存成功 !!");
					doFlag = false;
				} else {
					log.info("【期初+发生日终处理】信息保存失败 !!重新发起操作请求……");
				}
			} while (doFlag);

			re.setEntity("true");
			re.setMessage("执行成功");
		} else {
			log.info("本阶段需要处理的记录数：0 ");
			re.setEntity("true");
			re.setMessage("执行完成，本次无操作记录！");
		}
		log.info("【期初+发生日终处理】end !!");
		return re;
	}

	/**
	 * 
	 * description:  组装资金日终表数据
	 * @param list< UserFunds >
	 * @param nextDate
	 * @return  
	 * @author goldocean 
	 * @update 2015-05-26
	 */
	private List<SvmCaptionBalance> buildListSCB(List list, long nextDate) throws Exception {
		List<SvmCaptionBalance> listSCB = new ArrayList<SvmCaptionBalance>();
		List<FundsTemplate> listTemplates = Constants.getAllCaptionTemplate();//模板list
		for (int i = 0; i < list.size(); i++) {
			UserFundsVo uf = (UserFundsVo) list.get(i);
			for (FundsTemplate temp : listTemplates) {
				SvmCaptionBalance scbtmp = new SvmCaptionBalance();
				String captionId = temp.getCaption();
				String balance = String.valueOf(ReflectionUtils.getFieldValue(uf, captionId));//反射获取对应属性的值
				scbtmp.setCaptionId(captionId);
				scbtmp.setUserId(uf.getUserId());
				scbtmp.setBalance(Long.parseLong(balance));
				scbtmp.setDateTrade(nextDate);
				listSCB.add(scbtmp);
			}
		}
		return listSCB;
	}

	public static void main(String[] args) {
		try {

			UserFundsVo us = new UserFundsVo();
			us.setUserId("A000001");
			us.setM1(100L);
			us.setM2(200L);
			us.setM3(300L);
			us.setM4(400L);
			us.setM5(500L);
			us.setM6(600L);
			us.setCaptionId1("m1");
			us.setCaptionId2("m2");
			us.setCaptionId3("m3");
			us.setCaptionId4("m5");
			us.setCaptionId6("m6");

			List<UserFundsVo> list = new ArrayList<UserFundsVo>();
			list.add(us);

			FundsOpenAndOccurBalancePlugin fbp = new FundsOpenAndOccurBalancePlugin();

			List<SvmCaptionBalance> listSCB = fbp.buildListSCB(list, DateUtils.toLong(new Date()));
			for (SvmCaptionBalance cb : listSCB) {
				System.out.println(cb.getCaptionId() + "->" + cb.getUserId() + "->" + cb.getBalance() + "-->"
						+ cb.getDateTrade());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
